<template>
    <div>
        <el-drawer v-model="isShow" title="添加车辆信息" direction="rtl" @close="closeHandler" modal show-close with-header
            size="40%">
            <!-- 头部 -->
            <template #header>
                <h4>添加车辆信息</h4>
            </template>

            <!-- 身体 -->
            <template #default>
                <el-row>
                    <el-form :model="formData" ref="formRef" :rules="formRules" label-width="80px" :inline="true">
                        <el-col :span="12">
                            <el-form-item label="所属小区" prop="community_code">
                                <el-select v-model="formData.community_code" @change="changeValue" placeholder="请选择"
                                    clearable filterable>
                                    <el-option v-for="item in allCommunityList" :key="item.id" :value="item.code"
                                        :label="item.name">
                                    </el-option>
                                </el-select>
                            </el-form-item>

                            <el-form-item label="所属房产" prop="house_code">
                                <el-select v-model="formData.house_code" @change="changeHouse" placeholder="请选择" clearable
                                    filterable>
                                    <el-option v-for="item in houseList" :key="item.id" :value="item.code"
                                        :label="item.name">
                                    </el-option>
                                </el-select>
                            </el-form-item>

                            <el-form-item label="车辆名称" prop="name">
                                <el-input v-model="formData.name" placeholder="请输入"></el-input>
                            </el-form-item>

                            <el-form-item label="车辆颜色" prop="color">
                                <el-input v-model="formData.color" placeholder="请输入"></el-input>
                            </el-form-item>

                            <el-form-item label="车辆照片" prop="photo">
                                <ImageUpload v-model="formData.photo" :limit="1" :type="'vehicle'" />
                            </el-form-item>

                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="所属栋数" prop="building_code">
                                <el-select v-model="formData.building_code" @change="changeBuild" placeholder="请选择"
                                    clearable filterable>
                                    <el-option v-for="item in buildingList" :key="item.id" :value="item.code"
                                        :label="item.name">
                                    </el-option>
                                </el-select>
                            </el-form-item>

                            <el-form-item label="所属成员" prop="member_id">
                                <el-select v-model="formData.member_id" placeholder="请选择" clearable filterable>
                                    <el-option v-for="item in memberList" :key="item.id" :value="item.id"
                                        :label="item.name">
                                    </el-option>
                                </el-select>
                            </el-form-item>

                            <el-form-item label="车辆牌照" prop="license_plate">
                                <el-input v-model="formData.license_plate" placeholder="请输入"></el-input>
                            </el-form-item>

                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="formData.remark" placeholder="请输入"></el-input>
                            </el-form-item>

                        </el-col>

                    </el-form>
                </el-row>
            </template>

            <!-- 底部 -->
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="isShow = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit">确定</el-button>
                </div>
            </template>

        </el-drawer>
    </div>
</template>

<script setup>
import { ref, toRaw } from 'vue'
import { ElMessage } from 'element-plus';
import { addCarInfoApi, getCarInfoApi, getBuildListApi, getMemberListApi, editCarInfoApi } from '@/api/vehicle.js'
import { getBuildingApi } from '@/api/community.js'
import { useAllCommunityList, useBuildingList, useHouseList } from '@/hooks/index.js'

// ==================================

// 抽屉控制变量
const isShow = ref(false)
const formRef = ref()
const allCommunityList = useAllCommunityList()
const buildingList = ref([])
const houseList = ref([])
const memberList = ref([])
const emit = defineEmits(['updateList'])

// ====================================

// 表单数据
const defaultData = () => ({
    building_code: "",
    color: "",
    community_code: "",
    house_code: null,
    license_plate: "",
    member_id: null,
    name: "",
    photo: "",
    remark: ""
})

const formData = ref(defaultData())


// 表单校验规则
var carPhoneValid = (rule, value, callback) => {
    const plateNumber = /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1})$/
    if (plateNumber.test(value)) {
        callback()
    } else {
        callback(new Error('请输入正确的车牌号'))
    }
}


const formRules = {
    community_code: [{ required: true, message: '请选择', trigger: 'blur' }],
    building_code: [{ required: true, message: '请选择', trigger: 'blur' }],
    house_code: [{ required: true, message: '请选择', trigger: 'blur' }],
    member_id: [{ required: true, message: '请选择', trigger: 'blur' }],
    color: [{ required: true, message: '请输入', trigger: 'blur' }],
    name: [{ required: true, message: '请输入', trigger: 'blur' }],
    license_plate: [
        { required: true, message: '请输入', trigger: 'blur' },
        { validator: carPhoneValid, trigger: 'blur' }
    ],
}

// 添加提交事件
const onSubmit = async () => {
    try {
        // 1. 表单校验
        await formRef.value.validate()
        console.log(toRaw(formData.value));
        formData.value.id ? await editCarInfoApi(toRaw(formData.value)) : await addCarInfoApi(toRaw(formData.value))

        ElMessage.success('操作成功')

        isShow.value = false

        emit('updateList')
    } catch (error) {
        console.log(error);
    }
}


// 关闭事件
const closeHandler = () => {
    // 移除表单校验
    formRef.value.resetFields()
    // 重置表单数据
    formData.value = defaultData()
}


// 数据回显
const replyData = async (id) => {
    // console.log(id);
    let res = await getCarInfoApi(id)
    // console.log(res);
    formData.value = res.data
    // Object.assign(formData, {...res.data})
    isShow.value = true

}

const changeValue = async (val) => {
    formData.value.building_code = null
    let res = await getBuildingApi(val)
    // console.log(res);
    buildingList.value = res.data
}

const changeBuild = async (val) => {
    formData.value.house_code = null
    let res = await getBuildListApi(val)
    console.log(res);
    houseList.value = res.data
}

const changeHouse = async (val) => {
    formData.value.member = null
    let res = await getMemberListApi(val)
    console.log(res);
    memberList.value = res.data
}


defineExpose({
    isShow,
    replyData
})

</script>

<style lang="scss" scoped></style>
